package com.xauto.pioneer.appuser.activity.takeCar;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xauto.pioneer.appuser.MyApplication;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.activity.common.TakePhotoActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.model.ClientSetting;
import com.xauto.pioneer.appuser.model.Image;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.util.DbUtil;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.TimeUtil;
import com.xauto.pioneer.appuser.util.ViewUtil;
import com.xauto.pioneer.appuser.view.TopBar;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.xauto.pioneer.appuser.activity.common.TakePhotoActivity.DO_BIG_IMAGE;
import static com.xauto.pioneer.appuser.activity.common.TakePhotoActivity.UPLOAD_IMG;

/**
 * 加油界面
 * Created by Ellis.Li on 2017/5/17.
 */

public class RefuelActivity extends BaseActivity {
    @Bind(R.id.topBar)
    TopBar topBar;
    @Bind(R.id.ivIdInfo)
    ImageView ivIdInfo;
    @Bind(R.id.tvIdInfoTakePhoto)
    TextView tvIdInfoTakePhoto;
    @Bind(R.id.etAccountWithDrawAmount)
    EditText etAccountWithDrawAmount;
    @Bind(R.id.accountLinear)
    LinearLayout accountLinear;
    @Bind(R.id.tvIdInfoInvoice)
    TextView tvIdInfoInvoice;
    @Bind(R.id.tvIdInfoNext)
    TextView tvIdInfoNext;
    @Bind(R.id.operateLinear)
    LinearLayout operateLinear;
    @Bind(R.id.invoiceSuccessLinear)
    LinearLayout invoiceSuccessLinear;
    @Bind(R.id.hint_text)
    TextView hintText;
    @Bind(R.id.prompt_success_text)
    TextView promptSuccessText;
    @Bind(R.id.prompt_hint_text)
    TextView promptHintText;
    @Bind(R.id.ensure_text)
    TextView ensureText;
    @Bind(R.id.photo_hint_text)
    TextView photoHintText;
    @Bind(R.id.photo_hint2_text)
    TextView photoHint2Text;

    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    //加油前照片
    private String refuelPrePhoto = "";
    //加油后照片
    private String refuelAfterPhoto = "";
    String car_order_no = "";

    /**
     * 入口
     *
     * @param mContext
     */
    public static void startAction(Context mContext, String car_order_no) {
        Intent intent = new Intent(mContext, RefuelActivity.class);
        intent.putExtra("car_order_no", car_order_no);
        mContext.startActivity(intent);
    }

    @Override
    protected int getContentView() {
        return R.layout.ac_refuel;
    }

    @Override
    protected void initView() {
        topBar.showView(TopBar.TITLE, TopBar.LEFT_IMAGE_BTN);
        topBar.setText(TopBar.TITLE, "加油");
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //未选择图片之前 此按钮不能点击
        ViewUtil.GetViewShgape(tvIdInfoNext);
        tvIdInfoNext.setBackgroundResource(R.drawable.bg_btn_gray);
        ViewUtil.SetViewShgape(tvIdInfoNext);
        tvIdInfoNext.setClickable(false);

    }

    @Override
    protected void initData() {
        Log.e(TAG, "refuelCompanyName refuelCompanyName refuelCompanyName");
        car_order_no = getIntent().getStringExtra("car_order_no");
        imageLoader = ImageLoader.getInstance();
        options = MyApplication.getDisplayImageOptions(mContext, 0, R.mipmap.bg_default_gasonline_before);

        String refuelCompanyName = "";
        List<ClientSetting> clientSetting = DbUtil.getInstance(mContext).getDataList(ClientSetting.class);
        if((clientSetting != null) && (clientSetting.size()>0)) {
            for (int i = 0; i < clientSetting.size(); i++) {
                refuelCompanyName = clientSetting.get(clientSetting.size()- 1).getRefuel_company_name();
            }
        }
        tvIdInfoInvoice.setText(getString(R.string.refuel_invoice_info, refuelCompanyName));
    }

    @OnClick({R.id.tvIdInfoTakePhoto, R.id.tvIdInfoNext,R.id.ensure_text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvIdInfoTakePhoto:
                String ImageMessage="时间:"+ TimeUtil.getFormatTime()+"地点:"+""+"经纬度:";
                startActivityForResult(TakePhotoActivity.getTakePhotoStartIntent(mContext,
                        DO_BIG_IMAGE, 1, 1, 640, 640), UPLOAD_IMG);
                tvIdInfoTakePhoto.setText("点击重新进行拍照");
                break;
            case R.id.tvIdInfoNext:
                if (StringUtils.isEmpty(refuelAfterPhoto) && !StringUtils.isEmpty(refuelPrePhoto)) {
                    Log.e("进入","1");
                    hintText.setVisibility(View.GONE);
                    ivIdInfo.setImageResource(R.mipmap.bg_default_gasonline_before);
                    tvIdInfoTakePhoto.setText("请按照示意图的位置点击拍照");
                    photoHint2Text.setText("加油后照片");
                    photoHintText.setText(getString(R.string.photo_after_refuel));
                    tvIdInfoInvoice.setText(getString(R.string.hint_after_refuel));
                    accountLinear.setVisibility(View.VISIBLE);
                    tvIdInfoNext.setClickable(false);
                    ViewUtil.GetViewShgape(tvIdInfoNext);
                    tvIdInfoNext.setBackgroundResource(R.drawable.bg_btn_gray);
                    ViewUtil.SetViewShgape(tvIdInfoNext);
                }
                if (!StringUtils.isEmpty(refuelAfterPhoto) && !StringUtils.isEmpty(refuelPrePhoto)) {
                    Log.e("进入","2");
                    submitRefuelInfo();
                }
                break;
            case R.id.ensure_text:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == TakePhotoActivity.UPLOAD_SUCCESS) {
            if (data != null && data.getExtras() != null) {
//                Uri avatarUri = data.getExtras().getParcelable("PATH");
//                assert avatarUri != null;
                loadEditImage(data.getExtras().getString("PATH"));
            }
        }
    }

    private void loadEditImage(String path) {
        new LHttpLib().editImage(mContext, memberId, Constants.IMAGE_TYPE_REFUL, path, new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                final Image image = new Image().parse(jsonStatus.data.optJSONObject("image_info"));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvIdInfoNext.setClickable(true);
                        ViewUtil.GetViewShgape(tvIdInfoNext);
                        tvIdInfoNext.setBackgroundResource(R.drawable.bg_btn_green_selector);
                        ViewUtil.SetViewShgape(tvIdInfoNext);
                        if (StringUtils.isEmpty(refuelPrePhoto)) {
                            refuelPrePhoto = image.source;
                        } else {
                            if(accountLinear.getVisibility()==View.VISIBLE){
                            refuelAfterPhoto = image.source;}else{
                                refuelPrePhoto = image.source;
                            }
                        }
                        imageLoader.displayImage(image.source, ivIdInfo);
                    }
                });
            }
        });
    }

    private void submitRefuelInfo() {
        JSONObject car_refuel_info = new JSONObject();
        String account = etAccountWithDrawAmount.getText().toString().trim();

        try {
            if (StringUtils.isEmpty(account) || Double.parseDouble(account) == 0) {
                prompt("加油金额不能为空");
                return;
            }
            if (Integer.parseInt(account)>999) {
                prompt("加油金额不能大于实际使用金额");
                return;}
            JSONArray photos = new JSONArray();
            photos.put(refuelPrePhoto);
            photos.put(refuelAfterPhoto);
            car_refuel_info.put("car_refuel_amount", account);
            car_refuel_info.put("car_refuel_image_list", photos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        new LHttpLib().submitCarRefuel(mContext, memberId, car_order_no, car_refuel_info, new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        invoiceSuccessLinear.setVisibility(View.VISIBLE);
                        operateLinear.setVisibility(View.GONE);
                    }
                });
            }
        });
    }
}
